import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_myshop/router/application.dart';
import 'package:flutter_myshop/service/service_method.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:url_launcher/url_launcher.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 火热商品区页数,从0开始
  int page = 0;
  // 存储火热商品
  List hotAreaGoodList = [];

  // 请求火热商品区数据
  void _getHotGoods() async {
    print("请求火热商品数据$page........");
    await getHomePageBelowContent(page: page).then((val) {
      // 更新状态
      setState(() {
        hotAreaGoodList.addAll(val['data']['goods']);
        page++;
      });
    });
  }

  @override
  void initState() {
    print("初始化HomePage......");
    _getHotGoods();
    super.initState();
  }

  // 火爆商区部分代码
  Widget _warpGoods(context) {
    // 只要不为火爆商品List不为空
    if (hotAreaGoodList.length != 0) {
      List<Widget> goodWidgetList = hotAreaGoodList.map((item) {
        return Container(
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                right: BorderSide(color: Colors.black12, width: 0.5),
                top: BorderSide(color: Colors.black12, width: 0.5),
                bottom: BorderSide(color: Colors.black12, width: 0.5),
              ),
            ),
            width: ScreenUtil().setWidth(141),
            child: InkWell(
              onTap: () {
                // log
                print("点击了火爆商品");
                Application.router
            .navigateTo(context, "/detail?id=${item['id']}");
              },
              child: Column(
                children: <Widget>[
                  // 图片
                  Container(
                    height: ScreenUtil().setHeight(140),
                    child: Image.network(
                      item['image'],
                      fit: BoxFit.fill,
                    ),
                  ),
                  Text(
                    "${item['name']}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                          child: Text(
                        "¥ ${item['price']}",
                      )),
                      Expanded(
                        child: Text("¥ ${item['noDiscountedPrice']}",
                            textAlign: TextAlign.end,
                            style: TextStyle(
                              color: Colors.black26,
                              decoration: TextDecoration.lineThrough,
                            )),
                      )
                    ],
                  )
                ],
              ),
            ));
      }).toList();

      return Wrap(
        spacing: 0,
        children: goodWidgetList,
      );
    }
    // 无法拿到火爆商品
    else {
      print("无法拿到火爆商品的信息,请检查后台接口........");
      return Text("网络出错,请稍后再试");
    }
  }

  //main
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('商城首页')),
        // return就是展示的
        body: FutureBuilder(
          // 异步请求数据的Future
          future: getHomePageContent(),
          // 第二个参数就是异步调用结果
          builder: (context, response) {
            // 拿到数据
            if (response.hasData) {
              // 接收首页数据
              Map data = response.data['data'];

              // 得到轮播图需要的数据
              List swiperDataList = data['slides'];

              // 得到导航栏需要的数据
              List navigatorList = data['navigators'];

              // 得到广告banner
              String advImageAdd = data['advertesPicture']['PICTURE_ADDRESS'];

              // 得到店长信息
              String leaderImage = data['shopInfo']['leaderImage'];
              String leaderPhone = data['shopInfo']['leaderPhone'];

              // 得到推荐商品信息
              List goodList = data['recommendGoods'];

              // 楼层组件信息
              List floorList = data['floor'];
              List<Widget> floorWidgetList = [];
              // 制成楼层组件
              for (int i = 0; i < floorList.length; i++) {
                floorWidgetList.add(Floor(index: i, floorList: floorList));
              }

              // 展示的组件List
              List<Widget> showWidgetList = [
                // 轮播图
                HomePageSwiper(swiperDataList: swiperDataList),
                // 分隔线
                new Divider(),

                // 导航栏
                TopNavigator(navigatorList: navigatorList),
                // 分隔线
                new Divider(),

                // 广告
                ADBanner(advImageAdd: advImageAdd),
                // 分隔线
                new Divider(),

                // 店长电话
                LeaderPhone(image: leaderImage, phone: leaderPhone),
                // 分隔线
                new Divider(),

                // 商品推荐
                RecommendGoods(goodList: goodList),

                // 火爆专区标题
                HotAreaTitle(),
                // 火爆专区商品
                _warpGoods(context)
              ];

              // 展示楼层: 插入到倒数第三位
              showWidgetList.insertAll(
                  showWidgetList.length - 2, floorWidgetList);

              // 解决超出问题
              return EasyRefresh(
                child: Column(
                  children: showWidgetList,
                ),
                footer: MaterialFooter(),
                header: MaterialHeader(),
                onLoad: () {
                  _getHotGoods();
                  return null;
                },
                onRefresh: () {
                  print("刷新页面....");
                  hotAreaGoodList.clear();
                  return null;
                },
              );
            }
            // 还未拿到数据
            else {
              return Center(
                child: Text('正在请求数据,请等待一下'),
              );
            }
          },
        ));
  }
}

// 轮播图
class HomePageSwiper extends StatelessWidget {
  final List swiperDataList;
  // 接收轮播图数组,要求有image
  const HomePageSwiper({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      //高度一定要,不然报错
      height: ScreenUtil().setHeight(120),
      child: Swiper(
        // 轮播图数量
        itemCount: swiperDataList.length,
        // 构建轮播图,需要Image返回
        itemBuilder: (BuildContext context, index) {
          return Image.network(
            swiperDataList[index]['image'],
            fit: BoxFit.fill,
          );
        },
        // 自动播放
        autoplay: true,
      ),
    );
  }
}

/*
 * 顶部导航栏 
 */
class TopNavigator extends StatelessWidget {
  final List navigatorList;

  const TopNavigator({Key key, this.navigatorList}) : super(key: key);
  // 构架一个小组件
  Widget _gridViewItemUI(item) {
    return InkWell(
      onTap: () {
        print("点击了导航栏!");
      },
      child: Column(children: <Widget>[
        Image.network(
          item['image'],
          width: ScreenUtil().setWidth(40),
          fit: BoxFit.fill,
        ),
        Text(item['mallCategoryName'])
      ]),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(120),
      padding: EdgeInsets.all(0),
      // 网格布局
      child: GridView.count(
        crossAxisCount: 5,
        padding: EdgeInsets.all(4),
        // 需要展示组件队列,navigatorList是数据承载者,map进行数据UI化
        children: navigatorList.map((item) {
          return _gridViewItemUI(item);
        }).toList(),
      ),
    );
  }
}

/*
 * 广告栏组件 
 */
class ADBanner extends StatelessWidget {
  // 广告图片地址
  final String advImageAdd;

  const ADBanner({Key key, this.advImageAdd}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
        height: ScreenUtil().setHeight(42),
        width: ScreenUtil().setWidth(274),
        child: InkWell(
            onTap: () {
              print("点击了广告....");
            },
            child: Image.network(
              advImageAdd,
              fit: BoxFit.fill,
            )));
  }
}

/*
 * 店长电话组件
 */
class LeaderPhone extends StatelessWidget {
  final String image;
  final String phone;

  const LeaderPhone({Key key, this.image, this.phone}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(93),
      width: ScreenUtil().setWidth(274),
      child: InkWell(
        onTap: () {
          print("拨打店长电话,phone:$phone.....");
          _laucherPhone();
        },
        child: Image.network(
          image,
          fit: BoxFit.fill,
        ),
      ),
    );
  }

  // 打电话
  void _laucherPhone() async {
    String url = "tel:" + phone;
    // 可以打电话
    if (await canLaunch(url)) {
      // TODO: 暂时模拟打电话
      await launch(url);
    }
    // 不能
    else {
      throw 'Could not lauch $url';
    }
  }
}

// 商品推荐
class RecommendGoods extends StatelessWidget {
  // 接收商品与价格数据
  final List goodList;

  const RecommendGoods({Key key, this.goodList}) : super(key: key);

  // 横向展示商品
  Widget _goodList() {
    return Container(
        height: ScreenUtil().setHeight(120),
        child: ListView.builder(
          itemBuilder: (context, index) {
            return _goodItemView(context, index);
          },
          itemCount: goodList.length,
          scrollDirection: Axis.horizontal,
        ));
  }

  // 单个推荐栏
  Widget _goodItemView(context, index) {
    return InkWell(
      //点击事件
      onTap: () {
        print("点击了商品${goodList[index]['id']}");
        // 路由跳转
        Application.router
            .navigateTo(context, "/detail?id=${goodList[index]['id']}");
      },
      //组件
      child: Container(
          height: ScreenUtil().setHeight(116),
          width: ScreenUtil().setWidth(93),
          padding: EdgeInsets.all(8.0),
          decoration: BoxDecoration(
              color: Colors.white,
              border:
                  Border(left: BorderSide(width: 1.5, color: Colors.black12))),
          child: Column(
            children: <Widget>[
              // 商品图片
              Image.network(
                goodList[index]['image'],
                height: ScreenUtil().setHeight(90),
                fit: BoxFit.fill,
              ),
              // 现在价格
              Container(
                  height: ScreenUtil().setHeight(8),
                  child: Text(
                    "¥ ${goodList[index]['price']}",
                    style: TextStyle(fontSize: 10),
                  )),
              // 折扣前价格
              Container(
                  height: ScreenUtil().setHeight(8),
                  child: Text(
                    "¥ ${goodList[index]['noDiscountedPrice']}",
                    style: TextStyle(
                        decoration: TextDecoration.lineThrough, fontSize: 10),
                  ))
            ],
          )),
    );
  }

  // 商品推荐提示栏
  Widget _recommendText(String text) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      height: ScreenUtil().setHeight(22),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
      child: Text(
        text,
        style: TextStyle(
          // 201, 145, 161
          color: Color.fromARGB(255, 201, 145, 161),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            // 推荐提示文本
            _recommendText('商品推荐'),
            // 商品推荐展示
            _goodList(),
          ],
        ),
      ),
    );
  }
}

// 楼层标题
class FloorTitle extends StatelessWidget {
  // 图片地址
  final String image;

  const FloorTitle({Key key, this.image}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(73),
      child: Image.network(
        image,
        fit: BoxFit.fill,
      ),
    );
  }
}

// 楼层主体
class FloorBody extends StatelessWidget {
  final List goodList;

  const FloorBody({Key key, this.goodList}) : super(key: key);
  // 最多用的Text样式
  Widget _sliverText(String str) {
    return Text(
      str,
      maxLines: 1,
      style: TextStyle(color: Color.fromARGB(255, 157, 157, 157)),
    );
  }

  // 楼层小隔间
  Widget _smallRoom(index, context) {
    return InkWell(
        onTap: () {
          // log
          print("点击楼层小商品$index....");
          Application.router
              .navigateTo(context, "/detail?id=${goodList[index]['id']}");
        },
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white,
              border:
                  Border(bottom: BorderSide(width: 1, color: Colors.black12))),
          child: Column(
            children: <Widget>[
              Container(
                height: ScreenUtil().setHeight(18),
                alignment: Alignment.topLeft,
                child: Text(
                  goodList[index]['name'],
                  style: TextStyle(color: Color.fromARGB(255, 207, 24, 24)),
                ),
              ),
              Container(
                height: ScreenUtil().setHeight(56),
                child: Row(
                  children: <Widget>[
                    //介绍与价格
                    Expanded(
                      child: Column(
                        children: <Widget>[
                          Expanded(
                            child: Container(
                              alignment: Alignment.topLeft,
                              child: _sliverText(goodList[index]['intro']),
                            ),
                          ),
                          Expanded(
                              child: Container(
                            alignment: Alignment.bottomLeft,
                            child: _sliverText("¥ ${goodList[index]['price']}"),
                          ))
                        ],
                      ),
                    ),
                    //图片
                    Container(
                      height: ScreenUtil().setHeight(56),
                      width: ScreenUtil().setWidth(52),
                      child: Image.network(
                        goodList[index]['image'],
                        fit: BoxFit.fill,
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ));
  }

  // 大的商品展示
  Widget _bigRoom(index, context) {
    return InkWell(
        onTap: () {
          // log
          print("点击楼层大商品$index");
          Application.router
              .navigateTo(context, "/detail?id=${goodList[index]['id']}");
        },
        child: Container(
          decoration: BoxDecoration(
              color: Colors.white,
              border:
                  Border(bottom: BorderSide(width: 1, color: Colors.black12))),
          child: Column(
            children: <Widget>[
              // 第一行名称
              Container(
                height: ScreenUtil().setHeight(15),
                alignment: Alignment.topLeft,
                child: Text(
                  goodList[0]['name'],
                  style: TextStyle(
                      // 0, 162, 232
                      color: Color.fromARGB(255, 0, 162, 232)),
                ),
              ),
              Container(
                height: ScreenUtil().setHeight(15),
                child: Row(
                  children: <Widget>[
                    // 简介
                    Expanded(child: _sliverText(goodList[index]['intro'])),
                    // 价格
                    Container(
                      width: ScreenUtil().setWidth(50),
                      child: _sliverText("¥ ${goodList[index]['price']}"),
                      alignment: Alignment.topRight,
                    )
                  ],
                ),
              ),
              Expanded(
                child: Container(
                  child: Image.network(
                    goodList[index]['image'],
                    fit: BoxFit.fill,
                  ),
                ),
              )
            ],
          ),
        ));
  }

  // 上半层楼
  Widget _upFloor(context) {
    return Container(
      height: ScreenUtil().setHeight(159),
      child: Row(
        children: <Widget>[
          Expanded(child: _bigRoom(0, context)),
          Expanded(
              child: Column(
            children: <Widget>[
              Expanded(
                child: _smallRoom(1, context),
              ),
              Expanded(
                child: _smallRoom(2, context),
              ),
            ],
          )),
        ],
      ),
    );
  }

  // 下半层楼
  Widget _downFloor(context) {
    return Container(
      height: ScreenUtil().setHeight(80),
      child: Row(
        children: <Widget>[
          Expanded(child: _smallRoom(3, context)),
          Expanded(child: _smallRoom(4, context)),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          _upFloor(context),
          _downFloor(context),
        ],
      ),
    );
  }
}

// 楼层组件整体
class Floor extends StatelessWidget {
  final int index;

  final List floorList;

  const Floor({Key key, this.index, this.floorList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      children: <Widget>[
        FloorTitle(image: floorList[index]['title']['image']),
        FloorBody(goodList: floorList[index]['goods'])
      ],
    ));
  }
}

// 火爆专区标题
class HotAreaTitle extends StatelessWidget {
  // main 
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Container(
        alignment: Alignment.center,
        height: ScreenUtil().setHeight(20),
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                bottom: BorderSide(color: Colors.black12, width: 0.5),
                top: BorderSide(color: Colors.black12, width: 0.5))),
        child: Text(
          '火爆专区',
          style: TextStyle(color: Colors.red),
        ),
      ),
    );
  }
}
